const stickyUtils = window.markAnything.utils;

// 添加便签
const addStickyNote = async (content) => {
  try {
    await stickyUtils.checkStorageAvailable();
    const result = await chrome.storage.local.get(['stickyNotes']);
    const stickyNotes = result.stickyNotes || [];
    
    const note = {
      id: Date.now(),
      content,
      url: window.location.href,
      pageTitle: document.title,
      createdAt: new Date().toISOString()
    };
    
    // 添加到便签列表的开头
    stickyNotes.unshift(note);
    await chrome.storage.local.set({ stickyNotes });
    return note.id;
  } catch (error) {
    console.error('保存便签失败:', error);
    throw error;
  }
};

// 获取所有便签
const getAllStickyNotes = async () => {
  try {
    await stickyUtils.checkStorageAvailable();
    const result = await chrome.storage.local.get(['stickyNotes']);
    return result.stickyNotes || [];
  } catch (error) {
    console.error('获取便签失败:', error);
    throw error;
  }
};

// 删除便签
const deleteStickyNote = async (id) => {
  try {
    await stickyUtils.checkStorageAvailable();
    const result = await chrome.storage.local.get(['stickyNotes']);
    const stickyNotes = result.stickyNotes || [];
    const newNotes = stickyNotes.filter(note => note.id !== id);
    
    if (newNotes.length === stickyNotes.length) {
      throw new Error('便签不存在');
    }
    
    await chrome.storage.local.set({ stickyNotes: newNotes });
  } catch (error) {
    console.error('删除便签失败:', error);
    throw error;
  }
};

// 更新便签
const updateStickyNote = async (id, updates) => {
  try {
    await stickyUtils.checkStorageAvailable();
    const result = await chrome.storage.local.get(['stickyNotes']);
    const stickyNotes = result.stickyNotes || [];
    const noteIndex = stickyNotes.findIndex(note => note.id === id);
    
    if (noteIndex !== -1) {
      stickyNotes[noteIndex] = { ...stickyNotes[noteIndex], ...updates };
      await chrome.storage.local.set({ stickyNotes });
      return stickyNotes[noteIndex];
    }
    throw new Error('便签不存在');
  } catch (error) {
    console.error('更新便签失败:', error);
    throw error;
  }
};

// 显示便签编辑器
const showStickyNoteEditor = async () => {
  try {
    stickyUtils.closeAllPopups();
    const notes = await getAllStickyNotes();
    
    // 检查是否已存在编辑器
    const existingEditor = document.querySelector('.todo-input-container');
    if (existingEditor) {
      const isStickyNoteEditor = existingEditor.querySelector('h2').textContent === '便签';
      existingEditor.remove();
      // 如果关闭的是便签编辑器，则直接返回，不再创建新的
      if (isStickyNoteEditor) {
        return;
      }
    }

    const container = document.createElement('div');
    container.className = 'todo-input-container sticky-notes-container';

    // 阻止滚动事件传播
    container.addEventListener('wheel', (e) => {
      const target = e.target;
      // 检查滚动事件是否发生在可滚动元素内
      let isScrollable = false;
      let element = target;
      
      while (element !== container && element !== null) {
        if (element.scrollHeight > element.clientHeight) {
          isScrollable = true;
          break;
        }
        element = element.parentElement;
      }
      
      // 如果在可滚动元素内，且未到达滚动边界，则阻止事件传播
      if (isScrollable) {
        const scrollTop = element.scrollTop;
        const scrollHeight = element.scrollHeight;
        const clientHeight = element.clientHeight;
        
        // 检查是否到达滚动边界
        if ((scrollTop === 0 && e.deltaY < 0) || 
            (scrollTop + clientHeight >= scrollHeight && e.deltaY > 0)) {
          // 到达边界时不阻止，允许页面滚动
          return;
        }
        
        e.stopPropagation();
      }
    }, { passive: false });

    const header = document.createElement('div');
    header.className = 'todo-header';
    header.innerHTML = `
      <div class="todo-header-left">
        <h2>便签</h2>
        <div class="sticky-search-container">
          <input type="text" class="sticky-search-input" placeholder="搜索便签...">
          <button class="sticky-search-clear" title="清除搜索">×</button>
        </div>
      </div>
      <button class="todo-close-button">×</button>
    `;

    const searchInput = header.querySelector('.sticky-search-input');
    const searchClearBtn = header.querySelector('.sticky-search-clear');
    
    // 搜索功能实现
    const handleSearch = (searchText) => {
      const cards = notesList.querySelectorAll('.sticky-note-card');
      const emptyNote = notesList.querySelector('.sticky-notes-empty');
      
      if (emptyNote) {
        return;
      }
      
      let hasVisibleCards = false;
      
      cards.forEach(card => {
        const content = card.querySelector('.sticky-note-content');
        if (!content) return;
        
        const text = content.textContent.toLowerCase();
        const isMatch = text.includes(searchText.toLowerCase());
        card.style.display = isMatch ? '' : 'none';
        
        if (isMatch) {
          hasVisibleCards = true;
        }
      });
      
      // 显示或隐藏清除按钮
      searchClearBtn.style.display = searchText ? 'block' : 'none';
      
      // 如果没有匹配的结果，显示提示
      const noResultsEl = notesList.querySelector('.sticky-notes-no-results');
      if (!hasVisibleCards && searchText) {
        if (!noResultsEl) {
          const noResults = document.createElement('div');
          noResults.className = 'sticky-notes-no-results';
          noResults.textContent = '没有找到匹配的便签';
          notesList.appendChild(noResults);
        }
      } else if (noResultsEl) {
        noResultsEl.remove();
      }
    };
    
    // 添加搜索事件监听
    searchInput.addEventListener('input', (e) => handleSearch(e.target.value));
    
    // 清除搜索
    searchClearBtn.addEventListener('click', () => {
      searchInput.value = '';
      handleSearch('');
      searchInput.focus();
    });
    
    const contentWrapper = document.createElement('div');
    contentWrapper.className = 'sticky-notes-wrapper';

    // 创建新增便签按钮
    const addNoteButton = document.createElement('button');
    addNoteButton.className = 'add-sticky-note-button';
    addNoteButton.innerHTML = '+ 新建便签';
    
    // 便签列表容器
    const notesList = document.createElement('div');
    notesList.className = 'sticky-notes-list';

    contentWrapper.appendChild(addNoteButton);
    contentWrapper.appendChild(notesList);
    container.appendChild(header);
    container.appendChild(contentWrapper);
    document.body.appendChild(container);

    const closeButton = header.querySelector('.todo-close-button');
    closeButton.addEventListener('click', () => container.remove());

    // 创建新便签卡片的函数
    const createNewNoteCard = (isNew = false) => {
      const noteCard = document.createElement('div');
      noteCard.className = 'sticky-note-card' + (isNew ? ' new' : '');
      noteCard.style.backgroundColor = '#ffffff';
      
      const textarea = document.createElement('textarea');
      textarea.className = 'sticky-note-input';
      textarea.placeholder = '输入便签内容...';
      
      const actions = document.createElement('div');
      actions.className = 'sticky-note-actions';
      
      const saveButton = document.createElement('button');
      saveButton.className = 'sticky-note-save';
      saveButton.textContent = '保存';
      
      const cancelButton = document.createElement('button');
      cancelButton.className = 'sticky-note-cancel';
      cancelButton.textContent = '取消';
      
      actions.appendChild(saveButton);
      actions.appendChild(cancelButton);
      
      noteCard.appendChild(textarea);
      noteCard.appendChild(actions);
      
      // 添加到列表最前面
      notesList.insertBefore(noteCard, notesList.firstChild);
      textarea.focus();

      // 保存按钮事件
      saveButton.addEventListener('click', async () => {
        const content = textarea.value.trim();
        if (!content) {
          stickyUtils.showNotification('便签内容不能为空', true);
          return;
        }

        try {
          const id = await addStickyNote(content);
          noteCard.dataset.id = id;
          stickyUtils.showNotification('便签已保存');
          // 将编辑卡片转换为普通便签卡片
          createSavedNoteCard({ id, content, createdAt: Date.now() }, noteCard);
        } catch (error) {
          stickyUtils.showNotification('保存便签失败', true);
        }
      });

      // 取消按钮事件
      cancelButton.addEventListener('click', () => {
        noteCard.remove();
      });

      // 快捷键支持
      textarea.addEventListener('keydown', async (e) => {
        if (e.key === 'Enter' && (e.ctrlKey || e.metaKey || e.shiftKey)) {
          e.preventDefault();
          saveButton.click();
        } else if (e.key === 'Escape') {
          cancelButton.click();
        }
      });

      return noteCard;
    };

    // 创建已保存便签卡片的函数
    const createSavedNoteCard = (note, existingCard = null) => {
      const noteCard = existingCard || document.createElement('div');
      noteCard.className = 'sticky-note-card saved';
      noteCard.dataset.id = note.id;
      noteCard.style.backgroundColor = note.backgroundColor || '#ffffff';
      
      const content = document.createElement('div');
      content.className = 'sticky-note-content';
      content.textContent = note.content;
      
      const meta = document.createElement('div');
      meta.className = 'sticky-note-meta';
      meta.textContent = new Date(note.createdAt).toLocaleString();
      
      const actions = document.createElement('div');
      actions.className = 'sticky-note-actions';

      // 预设的颜色选项
      const colors = [
        { value: '#ffffff', title: '白色' },
        { value: '#fff8dc', title: '米色' },
        { value: '#f0fff0', title: '淡绿' },
        { value: '#f0f8ff', title: '淡蓝' },
        { value: '#fff0f5', title: '淡粉' }
      ];
      
      const colorButtons = document.createElement('div');
      colorButtons.className = 'sticky-note-colors';
      
      colors.forEach(color => {
        const button = document.createElement('button');
        button.className = 'sticky-note-color-btn';
        button.style.backgroundColor = color.value;
        button.title = color.title;
        if (color.value === note.backgroundColor) {
          button.classList.add('selected');
        }
        button.addEventListener('click', async () => {
          try {
            await updateStickyNote(note.id, { backgroundColor: color.value });
            noteCard.style.backgroundColor = color.value;
            note.backgroundColor = color.value;
            // 移除其他按钮的选中状态
            colorButtons.querySelectorAll('.sticky-note-color-btn').forEach(btn => {
              btn.classList.remove('selected');
            });
            // 添加当前按钮的选中状态
            button.classList.add('selected');
          } catch (error) {
            stickyUtils.showNotification('更新背景色失败', true);
          }
        });
        colorButtons.appendChild(button);
      });

      const editButton = document.createElement('button');
      editButton.className = 'sticky-note-edit';
      editButton.innerHTML = '✎';
      editButton.title = '编辑';
      
      const copyButton = document.createElement('button');
      copyButton.className = 'sticky-note-copy';
      copyButton.innerHTML = '⎘';
      copyButton.title = '复制';
      
      const deleteButton = document.createElement('button');
      deleteButton.className = 'sticky-note-delete';
      deleteButton.innerHTML = '×';
      deleteButton.title = '删除';
      
      actions.appendChild(colorButtons);
      actions.appendChild(editButton);
      actions.appendChild(copyButton);
      actions.appendChild(deleteButton);
      
      // 如果是转换已有卡片，先清空内容
      if (existingCard) {
        noteCard.innerHTML = '';
      }
      
      noteCard.appendChild(content);
      noteCard.appendChild(meta);
      noteCard.appendChild(actions);

      if (!existingCard) {
        notesList.appendChild(noteCard);
      }

      // 编辑按钮事件
      editButton.addEventListener('click', () => {
        noteCard.classList.add('editing');
        const input = document.createElement('textarea');
        input.className = 'sticky-note-edit-input';
        input.value = note.content;
        
        const editActions = document.createElement('div');
        editActions.className = 'sticky-note-edit-actions';
        
        const saveButton = document.createElement('button');
        saveButton.className = 'sticky-note-edit-save';
        saveButton.textContent = '保存';
        
        const cancelButton = document.createElement('button');
        cancelButton.className = 'sticky-note-edit-cancel';
        cancelButton.textContent = '取消';
        
        editActions.appendChild(saveButton);
        editActions.appendChild(cancelButton);
        
        content.style.display = 'none';
        noteCard.insertBefore(input, meta);
        actions.style.display = 'none';
        noteCard.appendChild(editActions);
        
        input.focus();
        
        const handleSave = async () => {
          const newContent = input.value.trim();
          if (newContent && newContent !== note.content) {
            note.content = newContent;
            content.textContent = newContent;
            try {
              await updateStickyNote(note.id, { content: newContent });
              stickyUtils.showNotification('更新成功');
            } catch (error) {
              stickyUtils.showNotification('更新失败', true);
            }
          }
          exitEditMode();
        };

        const exitEditMode = () => {
          noteCard.classList.remove('editing');
          content.style.display = '';
          input.remove();
          actions.style.display = '';
          editActions.remove();
        };
        
        saveButton.addEventListener('click', handleSave);
        cancelButton.addEventListener('click', exitEditMode);
        
        input.addEventListener('keydown', (e) => {
          if (e.key === 'Enter' && (e.ctrlKey || e.metaKey || e.shiftKey)) {
            e.preventDefault();
            handleSave();
          } else if (e.key === 'Escape') {
            exitEditMode();
          }
        });
      });

      // 其他按钮事件保持不变
      copyButton.addEventListener('click', () => {
        navigator.clipboard.writeText(note.content)
          .then(() => stickyUtils.showNotification('已复制到剪贴板'))
          .catch(() => stickyUtils.showNotification('复制失败', true));
      });

      deleteButton.addEventListener('click', async () => {
        try {
          await deleteStickyNote(note.id);
          noteCard.classList.add('deleting');
          setTimeout(() => {
            noteCard.remove();
            if (notesList.children.length === 0) {
              notesList.innerHTML = '<div class="sticky-notes-empty">暂无便签</div>';
            }
          }, 300);
          stickyUtils.showNotification('便签已删除');
        } catch (error) {
          stickyUtils.showNotification('删除失败', true);
        }
      });

      return noteCard;
    };

    // 新增便签按钮点击事件
    addNoteButton.addEventListener('click', () => {
      const emptyNote = notesList.querySelector('.sticky-notes-empty');
      if (emptyNote) {
        emptyNote.remove();
      }
      createNewNoteCard(true);
    });

    // 加载已有便签
    if (notes.length === 0) {
      notesList.innerHTML = '<div class="sticky-notes-empty">暂无便签</div>';
    } else {
      // 按创建时间降序排序
      notes.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
      notes.forEach(note => createSavedNoteCard(note));
    }
  } catch (error) {
    console.error('显示便签编辑器失败:', error);
    stickyUtils.showNotification('显示便签编辑器失败', true);
  }
};

// 导出到全局对象
window.markAnything.stickyRepository = {
  addStickyNote,
  getAllStickyNotes,
  deleteStickyNote,
  updateStickyNote,
  showStickyNoteEditor
};
